package com.ciwong.epaper.modules.epaper.dao;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.LswScoreResult;
import com.ciwong.epaper.modules.epaper.bean.LswUploadResult;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.RecordSubmitAsyncPart;
import com.ciwong.epaper.modules.epaper.bean.RecordSubmitPart;
import com.ciwong.epaper.util.DeviceUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.AsyncHttp.AsynHttpBaseRequest;
import com.ciwong.mobilelib.utils.BaseRequestUtil;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/16.
 */
public class LswRequest {


    private static final String TAG = "uploadmp3";


    public static void submitMakeScore(LswAnswer lswAnswer, boolean isCorrect, final BaseCallBack callBack) {

        AsynHttpBaseRequest asynHttpBaseRequest = new AsynHttpBaseRequest();

        RequestParams params = new RequestParams();


        if (null != lswAnswer.getAnswerContents() && lswAnswer.getAnswerContents().size() > 0) {

            int questionType = lswAnswer.getAnswerType();
            int qtype = lswAnswer.getQtype();

            AnswerContent answerContent = lswAnswer.getAnswerContents().get(0);
            if (questionType == Questions.AnswerType.QUESTION_TYPE_CHOICE || questionType == Questions.AnswerType.QUESTION_TYPE_FILL_BLANK) {

                return;

            } else {

                params.put("qtype", qtype);
                params.put("sessionId", lswAnswer.getWorkSaveUUid());
                params.put("versionId", lswAnswer.getVersionId());
                params.put("parentVersionId", lswAnswer.getParentVersionId());
                params.put("refAnswer", answerContent.getRefAnswer());
                params.put("refScore", lswAnswer.getRefScore());
                params.put("is_objective", lswAnswer.getIs_objective());
                params.put("bigQuesIndex", lswAnswer.getBigQuesIndex());
                params.put("quesNo", lswAnswer.getQuesNo());
                params.put("totalQuesIndex", lswAnswer.getTotalQuesIndex());
                if (isCorrect) {
                    params.put("doWorkId", lswAnswer.getDoWorkId());
                }

                String filePath = answerContent.getContent();
                if (null == filePath) {
                    callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                    return;
                }

                final File file = new File(filePath);

                if (file.exists() && file.length() > 0) {
                    Log.d(TAG, "file.length() ##########" + file.length());
                    try {

                        String contentType = "audio/mp3";
                        params.put("fileLength", file.length());
                        params.put("fileName", file.getName());
                        params.put("voice", file, contentType);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                    }
                } else {
                    callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                    return;
                }
                String action;
                if (isCorrect) {
                    action = EpaperAction.ACTION_LSW_UPLOAD_RECORRECT;
                } else {
                    action = EpaperAction.ACTION_LSW_UPLOAD_RECORD;
                }
                callBack.setUrl(action);
                asynHttpBaseRequest.request(Request.Method.POST, action, params, new AsynHttpBaseRequest.ResponseCallback() {

                    @Override
                    public void success(Object obj, int resultCode, int errorCode, String msg) {
                        if (resultCode == 0 && errorCode == 0) {
                            if (null != callBack)
                                callBack.success(obj);
                            Log.d(TAG, "##########success##########" + obj.toString());

                        } else {


                            Log.d(TAG, "##########success failed msg##########" + msg);
                            Log.d(TAG, "##########success 本地文件名：#########" + file.getName());

                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "本地文件名：" + file.getName() + "本地文件长度：" + file.length(), "发送与接收字节对不上");

                            if (null != callBack) {

                                callBack.failed(errorCode, msg);
                            }

                            //                            if (errorCode == 111)
                            {

                            }

                        }
                    }

                    @Override
                    public void error(int errorCode, String msg) {
                        callBack.failed(errorCode, msg);
                        Log.d(TAG, "########## 本地文件名：#########" + file.getName());
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "本地文件名：" + file.getName() + "本地文件长度：" + file.length(), "发送与接收字节对不上");
                        Log.d(TAG, "##########failed msg##########" + msg);
                    }

                }, RecordSubmitPart.class, null);


            }

        }
    }

    /**
     * 提交听说模考作业
     *
     * @param oldJson
     * @param doWorkType
     * @param callBack
     */
    public static void submitHomeWork(final String oldJson, int doWorkType, final BaseCallBack callBack) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_MODULES, EpaperAction.class.getName());
        if (doWorkType == 1) {
            //听说模考提交错题答案
            params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_LSW_SUBMIT_ERROR_WORKS);
        } else if (doWorkType == 2) {
            //听说模考提交的订正答案
            params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_LSW_RESUBMIT_WORKS);
        } else {
            //听说模考提交作业答案
            params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_LSW_SUBMIT_WORKS);
        }

        String sign = DeviceUtil.hmacSha1(oldJson.toString(), EConstants.HMACSHA1_SECRECT);
        params.put("sign", sign);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data", oldJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String answerJson = jsonObject.toString();

        HeadOverrideRequest request = new HeadOverrideRequest(Request.Method.POST, params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBack.failed(error);
                        if (callBack != null && error != null) {
                            FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, error.getMessage(), answerJson, "提交听说模考作业错误" + callBack.getUrl());
                        }
                    }
                }, new BaseRequest.ResponseCallback() {

            @Override
            public void error(int errorCode, String msg) {
                callBack.failed(errorCode, msg);
                if (callBack != null) {
                    FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, msg, answerJson, "提交听说模考作业错误" + callBack.getUrl());
                }
            }

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {

                    if (null != callBack)
                        callBack.success(obj);

                } else {

                    if (null != callBack) {
                        callBack.failed(errorCode, msg);
                        FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, msg, answerJson, "提交听说模考作业错误" + callBack.getUrl());
                    }
                }
            }
        }) {
            @Override
            public byte[] getBody() throws AuthFailureError {
                return answerJson.getBytes();
            }
        };

        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        //结果对象
        request.setResponseClazz(LswUploadResult.class);
        BaseRequestUtil.getInstance().add(request);
        callBack.setUrl(request.getUrl());
    }

    /**
     * 设置做作业进度
     *
     * @param answerJson
     * @param callBack
     */
    public static void onUploadDoworkProgress(final String answerJson, final BaseCallBack callBack) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(HttpRequest.REQUEST_MODULES, EpaperAction.class.getName());
        //由于新加接口
        params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_LSW_DOWORK_PROGRESS);


        HeadOverrideRequest request = new HeadOverrideRequest(Request.Method.POST, params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBack.failed(error);
                        if (callBack != null && error != null) {
                            FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, error.getMessage(), answerJson, "提交设置做作业进度错误" + callBack.getUrl());
                        }
                    }
                }, new BaseRequest.ResponseCallback() {

            @Override
            public void error(int errorCode, String msg) {
                callBack.failed(errorCode, msg);
                if (callBack != null) {
                    FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, msg, answerJson, "设置做作业进度错误" + callBack.getUrl());
                }
            }

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {
                if (resultCode == 0 && errorCode == 0) {

                    if (null != callBack)
                        callBack.success(obj);

                } else {

                    if (null != callBack) {
                        callBack.failed(errorCode, msg);
                        FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, msg, answerJson, "设置做作业进度作业错误" + callBack.getUrl());
                    }
                }
            }
        }) {
            @Override
            public byte[] getBody() throws AuthFailureError {
                return answerJson.getBytes();
            }
        };

        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        //结果对象
        request.setResponseClazz(Integer.class);
        BaseRequestUtil.getInstance().add(request);
        callBack.setUrl(request.getUrl());
    }

    /**
     * 获取听说模考作业或自主练习评分
     *
     * @param doworkId 提交作业或练习返回的doworkId, 不是workId
     */
    public static void getLswScoreResult(String doworkId, final BaseCallBack callBack) {

        Map<String, String> params = new HashMap<>();
        params.put(HttpRequest.REQUEST_MODULES, EpaperAction.class.getName());
        params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_LSW_GET_SCORE_RESULT);
        params.put("doWorkId", doworkId + "");

        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBack.failed(error);
                    }

                }, new BaseRequest.ResponseCallback() {

            @Override
            public void error(int errorCode, String msg) {
                callBack.failed(errorCode, msg);
            }

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {

                if (resultCode == 0 && errorCode == 0) {
                    callBack.success(obj);
                } else {
                    callBack.failed(errorCode, msg);
                }
            }
        });

        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(LswScoreResult.class);
        BaseRequestUtil.getInstance().add(request);
        callBack.setUrl(request.getUrl());
    }

    /**
     * 获取作文批改评分
     *
     * @param doworkId 提交作业或练习返回的doworkId, 不是workId
     */
    public static void getEssayScoreResult(String doworkId, final BaseCallBack callBack) {

        Map<String, String> params = new HashMap<>();
        params.put(HttpRequest.REQUEST_MODULES, EpaperAction.class.getName());
        params.put(HttpRequest.REQUEST_ACTION, EpaperAction.ACTION_ESSAY_GET_SCORE_RESULT);
        params.put("doWorkId", doworkId + "");

        HttpRequest request = new HttpRequest(params,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBack.failed(error);
                    }

                }, new BaseRequest.ResponseCallback() {

            @Override
            public void error(int errorCode, String msg) {
                callBack.failed(errorCode, msg);
            }

            @Override
            public void success(Object obj, int resultCode,
                                int errorCode, String msg) {

                if (resultCode == 0 && errorCode == 0) {
                    callBack.success(obj);
                } else {
                    callBack.failed(errorCode, msg);
                }
            }
        });

        request.setResponseDataType(HttpRequest.RESPONSE_DATA_TYPE_OBJECT);
        request.setResponseClazz(LswScoreResult.class);
        BaseRequestUtil.getInstance().add(request);
        callBack.setUrl(request.getUrl());
    }

    public static void submitAsyncMakeScore(LswAnswer lswAnswer, final BaseCallBack callBack) {
        AsynHttpBaseRequest asynHttpBaseRequest = new AsynHttpBaseRequest();
        RequestParams params = new RequestParams();
        if (null != lswAnswer.getAnswerContents() && lswAnswer.getAnswerContents().size() > 0) {
            int qtype = lswAnswer.getQtype();
            AnswerContent answerContent = lswAnswer.getAnswerContents().get(0);
            params.put("qtype", qtype);
            params.put("sessionId", lswAnswer.getWorkSaveUUid());
            params.put("versionId", lswAnswer.getVersionId());
            params.put("parentVersionId", lswAnswer.getParentVersionId());
            params.put("refAnswer", answerContent.getRefAnswer());
            params.put("refScore", lswAnswer.getRefScore());
            params.put("is_objective", lswAnswer.getIs_objective());
            String filePath = answerContent.getContent();
            if (null == filePath) {
                callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                return;
            }
            final File file = new File(filePath);
            if (file.exists() && file.length() > 0) {
                Log.d(TAG, "file.length() ##########" + file.length());
                try {
                    String contentType = "audio/mp3";
                    params.put("fileLength", file.length());
                    params.put("fileName", file.getName());
                    params.put("voice", file, contentType);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                }
            } else {
                callBack.failed(EpaperConstant.ERROR_CODE_RECORD_FILE_MISS, "录音文件不存在！");
                return;
            }
            String action = EpaperAction.ACTION_LSW_UPLOAD_ASYNC_RECORD;
            callBack.setUrl(action);
            asynHttpBaseRequest.request(Request.Method.POST, action, params, new AsynHttpBaseRequest.ResponseCallback() {
                @Override
                public void success(Object obj, int resultCode, int errorCode, String msg) {
                    if (resultCode == 0 && errorCode == 0) {
                        if (null != callBack)
                            callBack.success(obj);
                        Log.d(TAG, "##########success##########" + obj.toString());
                    } else {
                        Log.d(TAG, "##########success failed msg##########" + msg);
                        Log.d(TAG, "##########success 本地文件名：#########" + file.getName());
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "本地文件名：" + file.getName() + "本地文件长度：" + file.length(), "发送与接收字节对不上");
                        if (null != callBack) {
                            callBack.failed(errorCode, msg);
                        }
                    }
                }

                @Override
                public void error(int errorCode, String msg) {
                    callBack.failed(errorCode, msg);
                    Log.d(TAG, "########## 本地文件名：#########" + file.getName());
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "本地文件名：" + file.getName() + "本地文件长度：" + file.length(), "发送与接收字节对不上");
                    Log.d(TAG, "##########failed msg##########" + msg);
                }

            }, RecordSubmitAsyncPart.class, null);
        }
    }
}
